package com.hzmg.akkacloud.worker.background;

import akka.actor.ActorRef;
import akka.actor.Kill;
import akka.routing.Broadcast;
import com.google.common.collect.Maps;
import com.hzmg.akkacloud.common.model.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * loadBalance for actor and web.
 *
 * @author zbw
 * @since 2022/9/4
 */
@Slf4j
public class LoadBalanceService {
    //serviceInstance map,used by web balance.
    //TODO qjx go
    private static Map<String, ServiceInstance> appName2ServiceInstance = Maps.newConcurrentMap();

    //router map
    private static Map<String, ActorRef> routers = Maps.newConcurrentMap();

    /**
     *
     */
    public static void updateRouter(String name, ActorRef route) {
        if (routers.get(name) != null) {
            ActorRef actorRef = routers.get(name);
            actorRef.tell(new Broadcast(Kill.getInstance()), actorRef);
            routers.remove(name);
        }
        routers.putIfAbsent(name, route);
    }

    public static ActorRef getRouterByAppName(String appName) {
        return routers.get(appName);
    }

    public static void destoryRouter(String appName) {
        ActorRef actorRef = routers.get(appName);
        actorRef.tell(new Broadcast(Kill.getInstance()), actorRef);
        routers.remove(appName);
    }

    //TODO webIp load balance.

}
